package com.tech.service.util;

import com.tech.utils.DateUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementer;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * 唯一单号生成工具类
 *
 */
public class UniqueKeyGenerateUtil {

    private static MySQLMaxValueIncrementer payOrderGenerateNo;

    static {
        // web应用
//        WebApplicationContext ac = ContextLoader.getCurrentWebApplicationContext();
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
        payOrderGenerateNo = (MySQLMaxValueIncrementer) ac.getBean("PayOrderIncrementer");
    }

    private static String PAYORDERFLAG = "00";

    private static Integer POSTFIXL = 4;

    public static String getPayOrderNo() {
        return getKeyPrefix() + PAYORDERFLAG + getKeyPostfix(payOrderGenerateNo.nextStringValue());
    }


    private static String getKeyPrefix() {
        String dateStr = DateUtil.getCurrentTimeStr();
        return dateStr;
    }

    private static String getKeyPostfix(String str) {
        String strSub = str;
        if (str.length() >= POSTFIXL) {
            strSub = str.substring(str.length() - POSTFIXL);
        }

        return strSub;
    }

    public static void main(String[] args) {
        Long t1 = System.currentTimeMillis();
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < 100000; i++) {
            String orderNo = UniqueKeyGenerateUtil.getPayOrderNo();
            if (map.containsKey(orderNo)) {
                System.out.println("订单号已经重复--》" + orderNo + "i==" + i + "map-orderNo-->" + map.get(orderNo));
                break;
            } else {
                map.put(orderNo, orderNo);
            }
        }
        Long t2 = System.currentTimeMillis();
        System.out.println((t2 - t1) / 1000);
    }
}
